'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { useAuth } from '@/hooks/use-auth';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ProfileForm } from '@/components/profile/profile-form';
import { SecurityForm } from '@/components/profile/security-form';
import { Mail, Phone, Calendar, User2, BadgeCheck, AlertCircle } from 'lucide-react';
import { motion } from 'framer-motion';
import { FadeIn, SlideIn, ScaleIn } from '@/components/ui/motion';
import { getUserProfile, User } from '@/services/userService';
import { useRouter } from 'next/navigation';
import { isAuthenticated } from '@/services/api';

// 角色映射
const roleMap: { [key: string]: string } = {
  'ADMIN': '管理员',
  'TEACHER': '教师',
  'PARENT': '家长',
  'STUDENT': '学生'
};

export default function ProfilePage() {
  const { user: authUser } = useAuth();
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [authChecked, setAuthChecked] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState('basic');
  const router = useRouter();

  // 检查认证状态
  useEffect(() => {
    // 给认证状态一些时间加载
    const timer = setTimeout(() => {
      setAuthChecked(true);
      if (!isAuthenticated()) {
        router.push('/auth/login');
      }
    }, 500); // 延迟500ms，给认证状态加载的时间

    return () => clearTimeout(timer);
  }, [router]);

  // 获取用户信息
  useEffect(() => {
    // 只有在认证状态确认后才获取用户信息
    if (!authChecked || !isAuthenticated()) return;

    const fetchUserProfile = async () => {
      try {
        const userData = await getUserProfile();
        console.log('获取到的用户数据:', userData);
        setUser(userData);
        setError(null);
      } catch (error: any) {
        console.error('获取用户信息失败:', error);
        
        // 处理不同类型的错误
        if (error.response) {
          if (error.response.status === 401) {
            setError('登录已过期，请重新登录');
            // 延迟跳转到登录页
            setTimeout(() => {
              router.push('/auth/login');
            }, 2000);
          } else {
            setError(`获取用户信息失败: ${error.response.data?.message || '服务器错误'}`);
          }
        } else {
          setError('获取用户信息失败，请稍后重试');
        }
      } finally {
        setLoading(false);
      }
    };

    fetchUserProfile();
  }, [authChecked, router]);

  // 如果认证状态尚未检查完成，显示加载状态
  if (!authChecked || loading) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  // 如果未认证，将由第一个useEffect处理重定向
  if (!isAuthenticated()) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col justify-center items-center min-h-screen">
        <div className="bg-red-100 text-red-800 p-4 rounded-lg flex items-center mb-4">
          <AlertCircle className="w-5 h-5 mr-2" />
          <span>{error}</span>
        </div>
        <button 
          onClick={() => window.location.reload()} 
          className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors"
        >
          重试
        </button>
      </div>
    );
  }

  if (!user) return null;

  // 格式化日期
  const formatDate = (dateString: string | null | undefined) => {
    if (!dateString) return '未知日期';
    
    try {
      // 处理 ISO 格式的日期字符串
      const date = new Date(dateString);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '未知日期';
      }
      
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    } catch (e) {
      console.error('日期格式化错误:', e);
      return '未知日期';
    }
  };

  return (
    <FadeIn>
      <div className="container mx-auto py-8 px-4">
        <div className="max-w-4xl mx-auto space-y-8">
          {/* 个人资料头部 */}
          <ScaleIn>
            <Card className="overflow-hidden">
              <CardContent className="p-0">
                <div className="relative">
                  {/* 背景装饰 */}
                  <div className="absolute inset-0 bg-gradient-to-br from-blue-500 via-indigo-500 to-purple-500 h-48" />
                  
                  <div className="relative pt-12 px-6 pb-6">
                    <div className="flex flex-col items-center">
                      <div className="relative mb-8">
                        <Avatar className="w-28 h-28 ring-4 ring-white shadow-lg">
                          <AvatarImage src={user.avatar || undefined} alt={user.name} />
                          <AvatarFallback className="bg-gradient-to-br from-blue-400 to-purple-400 text-white text-2xl">
                            {user.name?.[0]}
                          </AvatarFallback>
                        </Avatar>
                        {user.enabled && (
                          <div className="absolute -bottom-1 -right-1 bg-green-500 text-white p-1.5 rounded-full shadow-md">
                            <BadgeCheck className="w-5 h-5" />
                          </div>
                        )}
                      </div>

                      <div className="text-center mb-10">
                        <h2 className="text-3xl font-bold text-gray-900 mb-2 drop-shadow-sm">{user.name}</h2>
                        <p className="text-gray-600">{user.username}</p>
                      </div>

                      <div className="w-full max-w-2xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="flex items-center gap-3 text-gray-600 bg-white/90 backdrop-blur-sm p-4 rounded-lg transition-all hover:bg-white hover:shadow-md">
                          <div className="bg-blue-100 p-2.5 rounded-lg">
                            <User2 className="w-5 h-5 text-blue-600" />
                          </div>
                          <span className="font-medium">{roleMap[user.role] || user.role}</span>
                        </div>
                        <div className="flex items-center gap-3 text-gray-600 bg-white/90 backdrop-blur-sm p-4 rounded-lg transition-all hover:bg-white hover:shadow-md">
                          <div className="bg-purple-100 p-2.5 rounded-lg">
                            <Mail className="w-5 h-5 text-purple-600" />
                          </div>
                          <span className="font-medium">{user.email || '未设置邮箱'}</span>
                        </div>
                        <div className="flex items-center gap-3 text-gray-600 bg-white/90 backdrop-blur-sm p-4 rounded-lg transition-all hover:bg-white hover:shadow-md">
                          <div className="bg-green-100 p-2.5 rounded-lg">
                            <Phone className="w-5 h-5 text-green-600" />
                          </div>
                          <span className="font-medium">{user.phone || '未设置手机'}</span>
                        </div>
                        <div className="flex items-center gap-3 text-gray-600 bg-white/90 backdrop-blur-sm p-4 rounded-lg transition-all hover:bg-white hover:shadow-md">
                          <div className="bg-orange-100 p-2.5 rounded-lg">
                            <Calendar className="w-5 h-5 text-orange-600" />
                          </div>
                          <span className="font-medium">{formatDate(user.createTime)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </ScaleIn>

          {/* 个人资料标签页 */}
          <SlideIn>
            <Card>
              <CardHeader>
                <CardTitle>个人资料设置</CardTitle>
              </CardHeader>
              <CardContent>
                <Tabs 
                  value={activeTab} 
                  onValueChange={setActiveTab}
                  className="w-full"
                >
                  <TabsList className="grid w-full grid-cols-2 mb-8">
                    <TabsTrigger 
                      value="basic"
                      className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-500 data-[state=active]:to-indigo-500 data-[state=active]:text-white transition-all duration-300"
                    >
                      基本信息
                    </TabsTrigger>
                    <TabsTrigger 
                      value="security"
                      className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-500 data-[state=active]:to-indigo-500 data-[state=active]:text-white transition-all duration-300"
                    >
                      安全设置
                    </TabsTrigger>
                  </TabsList>
                  <motion.div
                    key={activeTab}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.3 }}
                  >
                    <TabsContent value="basic" className="mt-6">
                      <ProfileForm user={user} />
                    </TabsContent>
                    <TabsContent value="security" className="mt-6">
                      <SecurityForm />
                    </TabsContent>
                  </motion.div>
                </Tabs>
              </CardContent>
            </Card>
          </SlideIn>
        </div>
      </div>
    </FadeIn>
  );
} 